package com.pachiraframework.springcloud.async.utils;

import java.util.Iterator;
import java.util.Map;
import java.util.concurrent.ConcurrentHashMap;

import javax.websocket.Session;

public class SessionUtils {
	
    /*<String,Session>的缓存*/  
    private static Map<String, Session> clients = new ConcurrentHashMap<String, Session>(); 
    
    public static String getClientId(String clientId){
  	  Iterator<String> it=clients.keySet().iterator();
  	  while(it.hasNext()){
  		  String info=it.next();
  		  if(info.equals(clientId)){
  			  return info;
  		  }
  	  }
  	  return null;
    }
    
    /**
     * 添加webSocket Session
     * @param clientId
     * @param session
     */
    public static void put(String clientId, Session session) {
        clients.put(clientId, session);  
    }  
  
    /**
     * 根据clientId获取webSocket Session
     * @param clientId
     * @return
     */
    public static Session get(String clientId) {
        return clients.get(clientId);  
    }  
  
    /**
     * 根据clientId 移除webSocket Session
     * @param clientId
     */
    public static void remove(String clientId) {  
        clients.remove(clientId);  
    }  
  
    /**
     * 根据Session移除Session
     * @param session
     */
    public static void remove(Session session) { 
        Iterator<Map.Entry<String, Session>> ito = clients.entrySet().iterator();  
        while (ito.hasNext()) {  
            Map.Entry<String, Session> entry = ito.next();  
            if (entry.getKey().equals(session))  
                remove(entry.getKey());  
        }  
    }  
  
    /**
     * 根据clientId 判断是否存在webSocket Session
     * @param clientId
     * @return
     */
    public static boolean hasConnection(String clientId) {
    	return clients.containsKey(clientId);  
    }  

    public static Map<String, Session> getAll(){
    	return clients;
    }
}
